package cn.tedu.micro.service.all.service.impl;

import cn.tedu.micro.service.all.mapper.OrderMapper;
import cn.tedu.micro.service.all.service.CartService;
import cn.tedu.micro.service.all.service.OrderService;
import cn.tedu.micro.service.all.service.StockService;
import cn.tedu.micro.service.pojo.param.OrderAddParam;
import cn.tedu.micro.service.pojo.po.OrderPO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockService stockService;
    @Autowired
    private CartService cartService;
    @Override
    public Boolean addOrder(OrderAddParam orderAddParam) {
        //新增订单入库之前-减少库存(是否充足)-删除购物车(对应用户的对应商品)
        //1.减少库存数
        Boolean stockResult = stockService.reduceStock(orderAddParam.getProductCode(), orderAddParam.getCount());
        if(!stockResult){
            return false; //程序到此终止
        }
        //2.删除购物中的商品
        Boolean  cartResult = cartService.deleteCart(orderAddParam.getProductCode(),orderAddParam.getUserId());
        if(!cartResult)
            return false;
        //3.新增订单到数据库中
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderAddParam,orderPO);
        orderPO.setOrderSn((new Date()).toString());
        int orderResult = orderMapper.insert(orderPO);
        if(!(orderResult>=1))
            return false;
        return true;
    }
}
